// admin/system/dao/sys_job_dao.go
package dao

import (
	"go-admin1/admin/system/model"
	"go-admin1/internal/infrastructure/database"
	"go-admin1/internal/infrastructure/logger"

	"go.uber.org/zap"
	"gorm.io/gorm"
)

// SysJobDao 定时任务数据访问接口
type SysJobDao interface {
	Create(job *model.SysJob) error
	GetByID(id int64) (*model.SysJob, error)
	Update(job *model.SysJob) error
	Delete(id int64) error
	List(page, pageSize int) ([]*model.SysJob, int64, error)
	ListAll() ([]*model.SysJob, error)
	ListByStatus(status string) ([]*model.SysJob, error)
}

type sysJobDao struct {
	db *gorm.DB
}

// NewSysJobDao 创建定时任务数据访问实例
func NewSysJobDao() SysJobDao {
	return &sysJobDao{
		db: database.GetDB(),
	}
}

func (j *sysJobDao) Create(job *model.SysJob) error {
	logger.Info("创建定时任务", zap.Int64("job_id", job.JobID))
	return j.db.Create(job).Error
}

func (j *sysJobDao) GetByID(id int64) (*model.SysJob, error) {
	logger.Debug("根据ID获取定时任务", zap.Int64("job_id", id))
	var job model.SysJob
	err := j.db.Where("job_id = ? AND status = '0'", id).First(&job).Error
	return &job, err
}

func (j *sysJobDao) Update(job *model.SysJob) error {
	logger.Info("更新定时任务", zap.Int64("job_id", job.JobID))
	return j.db.Save(job).Error
}

func (j *sysJobDao) Delete(id int64) error {
	logger.Info("删除定时任务", zap.Int64("job_id", id))
	return j.db.Where("job_id = ?", id).Delete(&model.SysJob{}).Error
}

func (j *sysJobDao) List(page, pageSize int) ([]*model.SysJob, int64, error) {
	logger.Debug("获取定时任务列表", zap.Int("page", page), zap.Int("page_size", pageSize))
	var jobs []*model.SysJob
	var total int64

	offset := (page - 1) * pageSize
	db := j.db.Model(&model.SysJob{}).Where("status = '0'")

	if err := db.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	if err := db.Offset(offset).Limit(pageSize).Find(&jobs).Error; err != nil {
		return nil, 0, err
	}

	return jobs, total, nil
}

func (j *sysJobDao) ListAll() ([]*model.SysJob, error) {
	logger.Debug("获取所有定时任务列表")
	var jobs []*model.SysJob
	err := j.db.Where("status = '0'").Find(&jobs).Error
	return jobs, err
}

func (j *sysJobDao) ListByStatus(status string) ([]*model.SysJob, error) {
	logger.Debug("根据状态获取定时任务列表", zap.String("status", status))
	var jobs []*model.SysJob
	err := j.db.Where("status = ?", status).Find(&jobs).Error
	return jobs, err
}
